package org.csu.jpetstore_cms.controller;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotBlank;
import org.csu.jpetstore_cms.pojo.Result;
import org.csu.jpetstore_cms.pojo.User;
import org.csu.jpetstore_cms.service.UserService;
import org.csu.jpetstore_cms.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/users")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    //test
    @GetMapping("/testRequest")
    public String test(@RequestParam("a") String a){
        return a;
    }
    @PostMapping("/testRequest1")
    public Result test2(){
        return Result.success("aaa");
    }
    //end



    @GetMapping("/hello")
    @ResponseBody
    public String hello(){
        return "hello";
    }
    @GetMapping("/login")
    public void login(HttpServletResponse response) throws IOException {
        response.sendRedirect("/html/login.html");

    }

    @GetMapping("/loginForm")
    public void loginForm(HttpServletResponse response) throws IOException {
        response.sendRedirect("/loginForm.html");
    }

    @PostMapping("/login")
    public Result login(
            @RequestParam("username") @NotBlank(message = "用户名不能为空") String username,
            @RequestParam("password") @NotBlank(message = "密码不能为空")  String password
    ){
        User loginUser = userService.findByUsername(username);
        if (loginUser!=null){
            if (loginUser.getPassword().equals(password)){
                Map<String,Object> claims = new HashMap<>();
                claims.put("username",loginUser.getName());
                claims.put("password",loginUser.getPassword());
                String jwt = JwtUtils.generateJwt(claims);
                return Result.success(jwt);
            }else{
                return Result.error("密码不正确！！！");
            }
        }
        else{
            return Result.error("用户不存在!!!");
        }
    }

}
